/**
 * 从本地打开文件的操作
 * @constructor
 */
let OpenFileWithNameAsync = (accept: string = "application/json", callback: (fileName: string, text: string) => void) => {
    const APPLICATION_JSON = "application/json";
    const TEXT_PLAIN = 'text/plain';
    const IMAGE_INFO = ''
    let inputFile = document.createElement('input');
    inputFile.type = "file";
    inputFile.accept = accept;
    inputFile.onchange = (e: any) => {
        if (e.currentTarget.files.length === 0) return;
        let file = e.currentTarget.files[0];
        console.log(file);
        let reader = new FileReader();
        let fileName = file.name;

        reader.onload = () => {
            let text = "";
            if (reader.result !== null) {
                if (accept.match(/.xlsx$/) !== null || accept.match(/.h5$/) !== null ||
                    accept.match(/.zip$/) !== null || accept === IMAGE_INFO) text = reader.result as string;
                else text = reader.result.toString();
            }
            if (accept !== APPLICATION_JSON) text = reader.result as string;
            callback(fileName, text);
        };
        reader.onerror = () => {
            callback(fileName, '读取失败');
        }
        if (accept === APPLICATION_JSON || accept === TEXT_PLAIN ||
            accept === '.fem' || accept === '.obj' || accept === '.igs' || accept === '.stp') reader.readAsText(file);
        else if (accept.match(/.xlsx$/) !== null || accept.match(/.h5$/) !== null ||
            accept.match(/.zip$/) !== null) reader.readAsArrayBuffer(file);
        else if (accept === IMAGE_INFO) {
            reader.readAsDataURL(file);
        }
        else reader.readAsDataURL(file);

    };
    document.body.appendChild(inputFile);
    inputFile.click();
    document.body.removeChild(inputFile);
};

let OpenFileWithName = (accept: string = "application/json") => new Promise<{fileName: string, text: string}>(resolve => {
    OpenFileWithNameAsync(accept, (fileName, text) => {
        resolve({fileName, text});
    });
});

export {OpenFileWithName, OpenFileWithNameAsync};